<template>
  <div class="personnel-entry-exit-application bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">停车场信息</h2>


    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchApplications" @reset="resetSearch" />
    </div>


    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <el-button type="primary" @click="openAddDialog">新增</el-button>
      <el-button type="danger" @click="deleteSelected">删除</el-button>
      <!-- <button @click="openImportDialog" class="btn btn-secondary">导入</button> -->
      <!-- <button @click="exportData(applications, '人员申请', selectedIds)" class="btn btn-secondary">导出</button> -->
    </div>


    <!-- Data Table -->

    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedApplications" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="PARKING_CODE" label="停车场编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PARKING_NAME" label="停车场名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EMPTY_LOT_NUM" label="空载车位数" header-align="center" align="center"></el-table-column>
        <el-table-column prop="HEAVY_LOT_NUM" label="重载车位数" header-align="center" align="center"></el-table-column>
        <el-table-column prop="OPEN_STATUS" label="开放状态" header-align="center" align="center">
          <template #default="scope">
            {{ scope.row.OPEN_STATUS == 1 ? '开放' : '关闭' }}
          </template>
        </el-table-column>
        <el-table-column prop="STAMP" label="备注" header-align="center" align="center"></el-table-column>

        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editApplication(scope.row)" link>编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->
    <Pagination v-if="applications.length" :tableData="applications" @alltabledata="alltabledata" />

    <!-- Add/Edit Dialog -->
    <el-dialog class="dialog-from" v-model="isDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'" width="650"
      destroy-on-close align-center>
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">

            <div v-if="isEditing">
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">停车场编码</label>
              <el-input type="text" id="staffCode" :disabled="true" v-model="formData.PARKING_CODE" required
                class="input" />
            </div>
            <div>
              <label for="staffName" class="block text-sm font-medium text-muted-foreground">停车场名称</label>
              <el-input type="text" id="staffName" v-model="formData.PARKING_NAME" required class="input" />
            </div>
            <div>
              <label for="idCard" class="block text-sm font-medium text-muted-foreground">空载车位数</label>
              <el-input type="text" id="idCard" v-model="formData.EMPTY_LOT_NUM" required class="input" />
            </div>
            <div>
              <label for="staffGender" class="block text-sm font-medium text-muted-foreground">重载车位数</label>
              <el-input type="text" id="TELEPHONE" v-model="formData.HEAVY_LOT_NUM" required class="input" />
            </div>
            <div>
              <label for="TELEPHONE" class="block text-sm font-medium text-muted-foreground">开放状态</label>
              <el-select v-model="formData.OPEN_STATUS" placeholder="请选择" clearable>
                <el-option label="开放" value='1' />
                <el-option label="关闭" value='0' />
              </el-select>
            </div>
          </div>
        </div>
        <!-- 其他信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>其他信息</span>
          </div>
          <div>
            <label class="block text-sm font-medium text-muted-foreground">备注：</label>
            <el-input type="text" v-model="formData.STAMP" required class="input" />
          </div>
        </div>
        <div class="mt-6 flex justify-end space-x-2">
          <el-button @click="closeDialog">取消</el-button>
          <el-button @click="handleSubmit" type="primary">确认</el-button>
        </div>
      </form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, getCurrentInstance } from 'vue'
import axios from 'axios'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()

import { dayjs } from "element-plus"
import { exportData, } from '#/utils/exportfile.js'
const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/hazardous-vehicle-park'
})

const search = ref({
  PARKING_CODE: '',
  OPEN_STATUS: ''
})
const formItems = ref([
  {
    label: '停车场编码:',
    model: 'PARKING_CODE',
    type: 'input',
    placeholder: '请输入',
  },

  {
    label: '开放状态：',
    model: 'OPEN_STATUS',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '开放', value: '1' },
      { label: '关闭', value: '0' },

    ],
  },

])
const loading = ref(false)
const applications = ref([])
const selectAll = ref(false)
const isDialogOpen = ref(false)

const isEditing = ref(false)
const formData = ref({

})
const viewingItem = ref(null)
const displayedApplications = ref([])
const alltabledata = (data) => {

  displayedApplications.value = data
}
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const rowKey = (row) => row.ID // 设置行的唯一标识

const selectedIds = ref([])
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const table = ref()
const searchApplications = async () => {
  try {
    displayedApplications.value = []
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    applications.value = response.data.map(app => ({ ...app, selected: false }))
    applications.value.forEach(element => {
      element.OPEN_STATUS = String(element.OPEN_STATUS)
    })
    updateSelectAllState()
  } catch (error) {
    console.error('搜索失败:', error)
    alert('搜索失败: ' + (error.response?.data?.message || error.message))
  }
}

const resetSearch = () => {
  search.value = {
    PARKING_CODE: '',
    OPEN_STATUS: ''
  }
  searchApplications()
}

const openAddDialog = () => {
  isDialogOpen.value = true
  isEditing.value = false
  formData.value = {}
}

const closeDialog = () => {
  isDialogOpen.value = false
}

const handleSubmit = async () => {






  if (!formData.value.PARKING_NAME) {
    alert('停车场名称不能为空')
    return
  }
  if (!formData.value.EMPTY_LOT_NUM) {
    alert('空载车位数不能为空')
    return
  }
  if (!formData.value.HEAVY_LOT_NUM) {
    alert('重载车位数不能为空')
    return
  }
  if (!formData.value.OPEN_STATUS) {
    alert('开放状态不能为空')
    return
  }





  formData.value.OPEN_STATUS = Number(formData.value.OPEN_STATUS)
  try {
    if (isEditing.value) {
      await axios.put(`${apiBaseUrl.value}/${formData.value.ID}`, formData.value)

    } else {
      await axios.post(`${apiBaseUrl.value}`, formData.value)

    }
    alert('提交成功')
    closeDialog()
    await searchApplications()
  } catch (error) {
    console.error('提交失败:', error)
    alert('提交失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {

  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(async item => {
        await axios.delete(`${apiBaseUrl.value}/${item.ID}`)
      }
      ))
      await alert('删除成功')
      selectedIds.value = []
      table.value.clearSelection()
      await searchApplications()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const editApplication = (item) => {
  formData.value = {
    ID: item.ID,
    PARKING_CODE: item.PARKING_CODE,
    EMPTY_LOT_NUM: item.EMPTY_LOT_NUM,
    HEAVY_LOT_NUM: item.HEAVY_LOT_NUM,
    OPEN_STATUS: item.OPEN_STATUS,
    PARKING_NAME: item.PARKING_NAME,
    STAMP: item.STAMP,

  }
  isEditing.value = true
  isDialogOpen.value = true
}



const toggleSelectAll = () => {
  console.log('触发全选:', !selectAll.value)
  selectAll.value = !selectAll.value
  applications.value.forEach(app => {
    app.selected = selectAll.value
    console.log(`设置 ${app.ID} 的选中状态为:`, app.selected)
  })
}

const toggleItemSelection = (item) => {
  console.log('切换选中状态:', item.ID, !item.selected)
  item.selected = !item.selected
  updateSelectAllState()
}

const updateSelectAllState = () => {

  selectAll.value = applications.value.length > 0 && applications.value.every(app => app.selected)

}




const getStatusClass = (status) => {
  const classMap = {
    '未审核': 'bg-yellow-100 text-yellow-800',
    '已通过': 'bg-green-100 text-green-800',
    '未通过': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

const importFile = ref(null)

const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}

const importData = () => {
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = '.xlsx, .xls, .csv'
  fileInput.style.display = 'none'

  fileInput.onchange = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = async (e) => {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const jsonData = XLSX.utils.sheet_to_json(worksheet)

      try {
        const response = await axios.post(`${apiBaseUrl.value}/import`, jsonData)
        alert(response.data.message || '导入成功')
        await searchApplications()
      } catch (error) {
        console.error('导入失败:', error)
        alert('导入失败: ' + (error.response?.data?.message || error.message))
      }
    }
    reader.readAsArrayBuffer(file)
  }

  document.body.appendChild(fileInput)
  fileInput.click()
  document.body.removeChild(fileInput)
}



function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF
  return buf
}


watch(applications, () => {

  updateSelectAllState()
}, { deep: true })

watch(selectAll, (newValue) => {
  // console.log('selectAll changed:', newValue)
  applications.value.forEach(app => {
    app.selected = newValue
    console.log('watch selectAll - 设置项目状态:', app.ID, app.selected)
  })
})

onMounted(() => {
  searchApplications()
})
</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.checkbox {
  @apply h-4 w-4 text-primary focus:ring-primary border-input rounded;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>

